package com.zhaojk.audio.service;

import com.zhaojk.audio.entity.PromptTemplate;
import com.zhaojk.audio.entity.TemplateVariable;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class TemplateProcessor {

    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{([^}]+)\\}");

    /**
     * 处理模板内容替换
     * @param template 模板对象
     * @param inputVars 用户提供的变量值（可选）
     * @return 替换后的完整提示词
     */
    public static String processTemplate(PromptTemplate template,
                                         Map<String, Object> inputVars) {
        // 安全转换（防御性编程）
        List<TemplateVariable> variables = Optional.ofNullable(template.getVariables())
                .orElse(Collections.emptyList());

        // 合并变量
        Map<String, Object> allVars = variables.stream()
                .filter(v -> v.getDefaultValue() != null)
                .collect(Collectors.toMap(
                        TemplateVariable::getName,
                        TemplateVariable::getDefaultValue,
                        (oldVal, newVal) -> newVal // 处理键冲突
                ));

        if (inputVars != null) {
            allVars.putAll(inputVars);
        }

        return replacePlaceholders(template.getTemplateContent(), allVars);
    }

    /**
     * 替换模板中的占位符
     */
    private static String replacePlaceholders(String template, Map<String, Object> variables) {
        StringBuffer result = new StringBuffer();
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);

        while (matcher.find()) {
            String placeholder = matcher.group(1);
            Object value = variables.getOrDefault(placeholder, "");
            matcher.appendReplacement(result, value.toString());
        }
        matcher.appendTail(result);

        return result.toString();
    }


}
